iT邦幫忙

2

[12 Project 學 Node.js] Project 1: Simple Web Server

  • 分享至 

  • xImage
  •  

Description:

  • Only using Node.js without Express or other thing.
  • HTML/Bootstrap

安裝Node.js

切換到Project目錄,初始化npm格式
npm init

參考Node.js官網範例

const http = require('http');

const hostname = '127.0.0.1';const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);});

兩種啟動server的方式

node server.js
npm start

手動撰寫web server,了解web server如何抓取html網頁

const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs'); //file system module

// setting user-defined type
const mineTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"
};

//create http server
http.createServer(function(req, res){
    var uri = url.parse(req.url).pathname;
    var fileName = path.join(process.cwd(), unescape(uri));
    console.log('Loading ' + uri);
    var stats;

    //check if the file is enter
    try{
        stats = fs.lstatSync(fileName);
    } catch(e) {
        res.writeHead(404, {'Content-type': 'text/plain'});
        res.write('404 Not Found!\n');
        res.end();
        return;
    }

    //get the file type to check is html type
    if(stats.isFile()){ //xxxx.xxxx.html (using reverse to make "html" in the index 0)
        console.log(path.extname(fileName));
        var mineType = mineTypes[path.extname(fileName).split(".").reverse()[0]];
        res.writeHead(200, {'Content-type': mineType});

        var fileStream = fs.createReadStream(fileName);
        fileStream.pipe(res);
    } else if(stats.isDirectory()){ //如果發現路徑是資料夾,則找index.html
        res.writeHead(302, {
            'Location': 'index.html'
        });
        res.end();
    } else{
        res.writeHead(500, {'Content-type': 'text/plain'});
        res.write('500 Internal Error\n');
        res.end();
    }
}).listen(1337);

在head include bootstrap css
<link rel="stylesheet" href="/css/bootstrap.css">

在 body 內加上以下html (從bootstrap抓example,修改成我們要的index.html內容)

    <nav class="navbar navbar-inverse">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">MyWebsite</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="index.html">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="services.html">Services</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

    <div class="container">
        <div class="row">
        <h1>Welcome</h1>
        <p>This is the welcome page</p>
        </div>

    </div><!-- /.container -->

create about.html & services.html
同樣套用index.html的html
每個頁面修改 li class 如下: (被選到頁面,class會是active)

<ul class="nav navbar-nav">
    <li><a href="index.html">Home</a></li>
    <li class="active"><a href="about.html">About</a></li>
    <li><a href="services.html">Services</a></li>
</ul>

之後有更方便的方法去套用bootstrap,不需要手動一個個加入


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言